package com.infinit.selfhelp.common.net.interceptor

import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import com.drake.channel.sendEvent
import com.drake.net.exception.NetUnknownHostException
import com.infinit.selfhelp.common.base.BaseViewModel
import com.infinit.selfhelp.common.event.TopMessage
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException

// 创建一个自定义拦截器，用于设置超时和统一处理超时异常
class NoNetworkInterceptor(val context: Context) : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        return try {
            if (isNetworkAvailable(context).not()) {
                sendEvent(TopMessage("No network available"))
                sendEvent(BaseViewModel.LoadingEvent(false))
            }
            chain.proceed(chain.request())
        } catch (e: NetUnknownHostException) {
            // 统一处理超时异常
            println("${e.message}")
            sendEvent(TopMessage("No network available"))
            throw e
        }
    }

    private fun isNetworkAvailable(context: Context): Boolean {
        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val network = connectivityManager.activeNetwork ?: return false
        val activeNetwork = connectivityManager.getNetworkCapabilities(network) ?: return false
        return when {
            activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
            activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
            activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
            else -> false
        }
    }
}